package com.quanyue.music.file.service.impl;

import com.quanyue.music.domain.constant.StatisticsType;
import com.quanyue.music.domain.entity.HotStyle;
import com.quanyue.music.file.mapper.StatisticsMapper;
import com.quanyue.music.file.service.StatisticsService;
import com.quanyue.music.file.type.*;
import com.quanyue.music.system.mapper.HotStyleMapper;
import com.shzisg.mybatis.mapper.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Collections;
import java.util.List;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    @Autowired
    private StatisticsMapper statisticsMapper;
    @Autowired
    private HotStyleMapper hotStyleMapper;

    @Override
    public Page<FMDetailLikeResult> findLikeCount(FMDetailLikeRequest request) {
        request.setOrderBy("start_time");
        request.setAsc(true);
        LocalDate date = LocalDate.parse(request.getDate());
        Page<FMDetailLikeResult> resultPage = statisticsMapper.findPlayMusic(date, request.getChannelNum(), request);
        resultPage.getContent().forEach(result -> {
            List<ZoneCount> zoneCountList;
            if (request.getStatisticsType().equals(StatisticsType.LIKE)) {
                zoneCountList = statisticsMapper.findLikeCount(result.getFmId());
            } else {
                zoneCountList = statisticsMapper.findListenCount(result.getFmId());
            }
            if (zoneCountList.isEmpty()) {
                result.setZoneCounts(Collections.EMPTY_LIST);
            } else {
                result.setZoneCounts(zoneCountList);
                result.setTotalCount(zoneCountList.stream()
                        .mapToInt(zoneLikeCounts -> {
                            return zoneLikeCounts.getCount();
                        }).sum());
            }
        });

        return resultPage;
    }

    @Override
    public List<FMHotResult> findHot(HotStatisticsRequest request) {
        LocalDate date = LocalDate.parse(request.getDate());
        List<FMHotResult> fmHotResults = statisticsMapper.findPlayList(date, request.getFmChannel());
        List<HotStyle> style = hotStyleMapper.findAllValid();
        fmHotResults.forEach(result -> {
            for (HotStyle hotStyle : style) {
                if (result.getTotalCount() >= hotStyle.getStartValue() && result.getTotalCount() < hotStyle.getEndValue()) {
                    result.setHotKey(hotStyle.getHotKey());
                    break;
                }
            }
        });
        return fmHotResults;
    }
}
